注意:所有文章除特别说明外,转载请注明出处.
Spring源码 - Spring IoC核心流程
1.初始化
Spring IoC的初始化过程很复杂,大致过程就是读取XML文件,然后解析XML文件,最终注册到BeanFactory中去。
xml -读取-> Resource -解析-> BeanDefinition -注册-> BeanFactory
初始化过程完成之后,Bean就存在与BeanFactory中可以被调用。
1 准备
1.1 详细的Spring IoC初始化过程
<bean id="Aaron" class="com.springstudy.talentshow.SuperInstrumentalist">
<property name="instruments">
<list>
<ref bean="piano"/>
<ref bean="saxophone"/>
</list>
</property>
</bean>
提示:加载时需要读取|解析|注册bean。
1.2 加载配置文件
在调用 ClassPathXmlApplicationContext 后,先会将配置位置信息保存到 configLocations ,供后面解析使用,之后,会调用 AbstractApplicationContext 的 refresh 方法进行刷新。
//构造器
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
super(parent);
//保存位置信息
this.setConfigLocations(configLocations);
if (refresh) {
//刷新
this.refresh();
}
}
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
1.3 创建载入BeanFactory
protected final void refreshBeanFactory() throws BeansException {
// ... ...
DefaultListableBeanFactory beanFactory = createBeanFactory();
// ... ...
loadBeanDefinitions(beanFactory);
// ... ...
}
1.4 创建XMLBeanDefinitionReader
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
throws BeansException, IOException {
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
2 读取
2.1 创建处理每个Resource
public int loadBeanDefinitions(String location, Set<Resource> actualResources)
throws BeanDefinitionStoreException {
// ... ...
// 通过Location来读取Resource
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
int loadCount = loadBeanDefinitions(resources);
// ... ...
}
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int counter = 0;
for (Resource resource : resources) {
// 载入每一个resource
counter += loadBeanDefinitions(resource);
}
return counter;
}
2.2 处理xml每个元素
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
// ... ...
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
// 处理每个xml中的元素,可能是import、alias、bean
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele);
}
}
}
// ... ...
}
2.3 解析和注册bean
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
// 将XML的元素解析为BeanDefinition存储到BeanDefinitionHolder
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// 注册 将BeanDefinition实例put到BeanFactory
// Register the final decorated instance.
BeanDefinitionReaderUtils.registerBeanDefinition(
bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
3 解析
3.1 处理每个Bean的元素
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, BeanDefinition containingBean) {
// ... ...
// 创建beandefinition
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
parseMetaElements(ele, bd);
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
// 处理“Constructor”
parseConstructorArgElements(ele, bd);
// 处理“Preperty”
parsePropertyElements(ele, bd);
parseQualifierElements(ele, bd);
// ... ...
}
3.2 处理属性的值
public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {
String elementName = (propertyName != null) ?
"<property> element for property '" + propertyName + "'" :
"<constructor-arg> element";
// ... ...
if (hasRefAttribute) {
// 处理引用
String refName = ele.getAttribute(REF_ATTRIBUTE);
if (!StringUtils.hasText(refName)) {
error(elementName + " contains empty 'ref' attribute", ele);
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(ele));
return ref;
}
else if (hasValueAttribute) {
// 处理值
TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
valueHolder.setSource(extractSource(ele));
return valueHolder;
}
else if (subElement != null) {
// 处理子类型(比如list、map等)
return parsePropertySubElement(subElement, bd);
}
// ... ...
}
4 注册
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
// ......
// 将beanDefinition注册
this.beanDefinitionMap.put(beanName, beanDefinition);
// ......
}
总结:注册的实质就是以beanName为key,以beanDefinition为value,将其put到HashMap的过程。
2.注入依赖
在IoC容器完成初始化之后,如果bean没有设置lazy-init属性,那么bean的实例就会在初始化IOC完成之后,及时地进行初始化。初始化时会先建立实例,然后根据配置利用反射对实例进行进一步操作。
初始化IoC容器 -> 初始化Bean -> 创建Bean实例 -> 注入Property
在创建Bean和注入Bean属性时,都是在doCreateBean()函数中进行的。
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd,
final Object[] args) {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 创建bean的实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// ... ...
// Initialize the bean instance.
Object exposedObject = bean;
try {
// 初始化bean的实例,如注入属性
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
// ... ...
}